package com.cty.SearchAlgorithms;

import java.util.ArrayList;
import java.util.List;

/*
 *
 * 二分查找(注意:二分查找必须是有序数组)
 *
 * */
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {1, 8, 9, 3, 3, 3, 10, 50};
        List<Integer> resIndexList = binarySearch(arr, 0, arr.length - 1, 3);
        System.out.println("找到了，下标为" + resIndexList);
    }

    //参数：arr数组，left左索引，right:右索引，findVal:要找的数据,返回值：目标值的索引集合
    public static List<Integer> binarySearch(int[] arr, int left, int right, int findVal) {
        //先判断是否找到数据,未找到返回-1
        if (left > right) {
            return new ArrayList<Integer>();
        }
        int mid = (right + left) / 2;
        if (arr[mid] > findVal) {//中间索引对应的值大于要找的值，向左递归
            return binarySearch(arr, left, mid - 1, findVal);
        } else if (arr[mid] < findVal) {//中间索引对应的值小于要找的值，向右递归
            return binarySearch(arr, mid + 1, right, findVal);
        } else {
            //出现多个值符合条件的情况
            int temp = mid - 1;
            //用于存放索引
            List<Integer> resIndexList = new ArrayList<>();
            //向左扫描
            while (true) {
                if (temp < 0 || arr[temp] != arr[mid]) {
                    break;
                }
                resIndexList.add(temp);
                temp--;
            }
            resIndexList.add(mid);
            temp = mid + 1;
            while (true) {
                if (temp > arr.length - 1 || arr[temp] != arr[mid]) {
                    break;
                }
                resIndexList.add(temp);
                temp++;
            }
            return resIndexList;
        }
    }
}
